package com.contexticon.SearchDemo;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import com.contexticon.mediaTest.PlayerTest;
import com.contexticon.model.Utterance;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;

import lucene.UtteranceDatabase;

public class SearchDemo extends JFrame {

	private JPanel contentPane;
	private JTextField txtTypeSearchQuery;
	private JTable table;
	public static PlayerTest playerTest;
	public static UtteranceDatabase uDb;
	public static Utterance[] uArray;
	private Toolkit toolKit = Toolkit.getDefaultToolkit();

	String[] transcriptPaths = {
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/HIMYM Pilot (full transcript).xml",
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/Obama Speech (full transcript).xml",
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/24 Pilot (full transcript).xml"
			//"C://Users//Till//Documents//Dropbox//Contexticon (shared)//Transcripts//HIMYM Pilot (full transcript).xml.xml",
			//"C://Users//Till//Documents//Dropbox//Contexticon (shared)//Transcripts//Obama Speech (full transcript).xml",
			//"C://Users//Till//Documents//Dropbox//Contexticon (shared)//Transcripts//24 Pilot (full transcript, end times corrected).xml",
			//"C://Users//Till//Documents//Dropbox//Contexticon (shared)//Transcripts//RHCP - Don't Forget Me.xml",
			//"C://Users//Till//Documents//Dropbox//Contexticon (shared)//Transcripts//TED - Susan Blackmore (full transcript).xml"
	};
	String[] mediaPaths = {
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/HIMYM Pilot.avi",
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/Obama Speech.mp4",
			"/Users/dglodzik/Dropbox/Contexticon (shared)/Transcripts/24 Pilot.avi",
			//"C:\\Users\\Till\\Documents\\Dropbox\\Contexticon (shared)\\Transcripts\\HIMYM Pilot.avi",
			//"C:\\Users\\Till\\Documents\\Dropbox\\Contexticon (shared)\\Transcripts\\Obama Speech.mp4",
			//"C:\\Users\\Till\\Documents\\Dropbox\\Contexticon (shared)\\Transcripts\\24 Pilot.avi",
			//"C:\\Users\\Till\\Documents\\Dropbox\\Contexticon (shared)\\Transcripts\\RHCP - Don't Forget Me.avi",
			//"C:\\Users\\Till\\Documents\\Dropbox\\Contexticon (shared)\\Transcripts\\TED - Susan Blackmore.mp4"
	};
	String[] titles = {
			"How I Met Your Mother (Pilot)",
			"Obama speech",
			"24 (Pilot)",
			"Red Hot Chili Peppers - Don't Forget Me",
			"TED - Memetics"
		};		
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SearchDemo frame = new SearchDemo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SearchDemo() {
		
		try {
		   // UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
		setMinimumSize(new Dimension(400, 300));
		setTitle("Contexicon Search");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// Position Searcher on right side of screen
		final Dimension screenSize = toolKit.getDefaultToolkit().getScreenSize();
		setBounds(((screenSize.getSize().width)/2), 0, ((screenSize.getSize().width)/2), screenSize.getSize().height-275);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		JMenu mnEdit = new JMenu("Edit");
		menuBar.add(mnEdit);
		
		JMenu mnView = new JMenu("View");
		menuBar.add(mnView);
		
		JMenu mnOptions = new JMenu("Options");
		menuBar.add(mnOptions);
		
		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		txtTypeSearchQuery = new JTextField();
		txtTypeSearchQuery.setSelectionEnd(50);
		txtTypeSearchQuery.setText("Type search query here...");
		txtTypeSearchQuery.setColumns(10);
		txtTypeSearchQuery.selectAll();
		
		JButton btnSearch = new JButton("Search!");
		// hit button by pressing ENTER
		btnSearch.registerKeyboardAction(btnSearch.getActionForKeyStroke(
                KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        btnSearch.registerKeyboardAction(btnSearch.getActionForKeyStroke(
                KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
                JComponent.WHEN_FOCUSED);

		
		JScrollPane scrollPane = new JScrollPane();
		
		table = new JTable();
		table.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null, null, null},
			},
			new String[] {
				"Play", "Type", "Title", "Utterance"
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, Object.class, Object.class, Object.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		});
		
		// hide last column ('Fidelity') for now
		//table.getColumnModel().removeColumn(table.getColumnModel().getColumn(4));		
		
		// Adjust columns
		table.setAutoResizeMode(table.AUTO_RESIZE_LAST_COLUMN);
		table.getColumnModel().getColumn(0).setMinWidth(55);
		table.getColumnModel().getColumn(0).setPreferredWidth(55);
		table.getColumnModel().getColumn(1).setMinWidth(55);
		table.getColumnModel().getColumn(1).setPreferredWidth(55);
		table.getColumnModel().getColumn(2).setMinWidth(40);
		table.getColumnModel().getColumn(2).setPreferredWidth(120);
		table.getColumnModel().getColumn(3).setPreferredWidth(600);
		((DefaultTableModel)table.getModel()).setRowCount(0);
		scrollPane.setViewportView(table);
		
		// Make table sortable
		final TableRowSorter sorter = new TableRowSorter(table.getModel());
		table.setRowSorter(sorter);
		
		JButton btnAddFilter = new JButton("Add Filters >>");
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
						.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
							.addContainerGap()
							.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 681, Short.MAX_VALUE))
						.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
							.addGap(5)
							.addComponent(txtTypeSearchQuery, GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
							.addGap(9)
							.addComponent(btnSearch))
						.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
							.addContainerGap()
							.addComponent(btnAddFilter)))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(6)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnSearch)
						.addComponent(txtTypeSearchQuery, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnAddFilter)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE))
		);
		contentPane.setLayout(gl_contentPane);
		
		// add the play button
		TableColumn buttonColumn = table.getColumnModel().getColumn(0);

        TableButton buttons = new TableButton();
        buttons.addHandler(new TableButton.TableButtonPressedHandler() {
			
			@Override
			public void onButtonPress(int row, int column) {
				// TODO Auto-generated method stub
				
				// access the utterance whose row was clicked
				Utterance anUtterance = uArray[row];
				
				// play the relevant media
				playerTest.playMedia(mediaPaths[anUtterance.getMovieId()], anUtterance.getStartTime()/1000, anUtterance.getEndTime()/1000);
				//playerTest.playMedia(mediaPaths[anUtterance.getMovieId()]);
				//System.out.println("Playing now: " + mediaPaths[anUtterance.getMovieId()]);
				// make it stop at the end of the utterance
				
				
			}
		});
        
        buttonColumn.setCellRenderer(buttons);
        buttonColumn.setCellEditor(buttons);
		
		
		// set the vlcj paths
		File file = new File("/Applications/VLC.app/Contents/MacOS/lib/");
		if (file.exists()) {
			System.setProperty("jna.library.path",
					"/Applications/VLC.app/Contents/MacOS/lib/");
		} else {
			System.setProperty("jna.library.path",
					"C:\\Users\\Till\\Desktop\\VLC builds\\Win64\\");
		}
		playerTest = new PlayerTest();
		
		// index the transcripts
		uDb = new UtteranceDatabase("");
		uDb.indexTranscrirpts(transcriptPaths, mediaPaths, titles);
	
		// search button
		btnSearch.addActionListener(new ActionListener() {
	        @Override
	        public void actionPerformed(ActionEvent e) {
	      	  
	        	// search through lucene
	    		String searchQuery = txtTypeSearchQuery.getText();
	    		
	    		// making searches beginning with * possible
	    		// needs to be modified to work with any word
	    		// within the query that begins with *
	    		String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
	    		if (searchQuery.startsWith("*")) {
	    			
	    			String tempSearchQuery = searchQuery;
	    			searchQuery = "";
	    			
	    			// iterate through all characters in 'alphabet'
	    			for (int i = 0; i < alphabet.length(); i++){
	    			    char c = alphabet.charAt(i);        
	    			    
	    			    // build search query
	    			    searchQuery = searchQuery + " " + c + tempSearchQuery;	    			    
	    			    
	    			}

	    		}
	    		System.out.println("Search Query: " + searchQuery);
	    		uArray = uDb.search(searchQuery);
	    		
	    		// clear the table
	    		((DefaultTableModel)table.getModel()).setRowCount(0);
	    		
	    		// loop over the search results
	    		for (int u=0; u<uArray.length; u++) {
	    			// add a new row to the table
	    			((DefaultTableModel)table.getModel()).addRow(new Object[] {
	    					"Play", 
	    					"Video",
	    					titles[uArray[u].getMovieId()], // Media Title
	    					uArray[u].getText(), ""}); // Utterance Text
	    		}
	      	  
	        }
	      });
	    
	    
		
	} // end of constructor
	
	
	
	
}
